package com.inspur.gs.sbssdl.database.sso.sso.back.util;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class JsonUtils {


    public static Map<String, Object> parse(JSONObject object){
        StringBuilder key = new StringBuilder();
        Map<String, Object> result = new HashMap<>();
        parseJson(object, key, result);
        return result;
    }
    /**
     * 遍历 JSONObject
     * 例如{"a":{"b","1"}} 输出 a.b=1
     * @param object 被遍历的JSONObject
     * @param key    层级key
     */
    private static void parseJson(JSONObject object, StringBuilder key, Map<String, Object> result) {
        for (Map.Entry<String, Object> stringObjectEntry : object.entrySet()) {
            String currentKey = (String) ((Map.Entry) stringObjectEntry).getKey();
            // son
            if (currentKey.contains(".")) continue;
            key.append(".").append(currentKey);
            Object value = stringObjectEntry.getValue();
            if (value instanceof JSONObject) {
                // 如果值为json对象，则继续解析
                JSONObject jsonValue = (JSONObject) value;
                parseJson(jsonValue, key, result);
            } else {
                result.put(key.toString().substring(1), value);
                // 移除最后一个节点
                key.delete(key.lastIndexOf("."), key.length());
            }
        }
        if(key.length() > 0){
            key.delete(key.lastIndexOf("."), key.length());
        }

    }
}
